package com.xhj.springbootproject.controller;

import com.xhj.springbootproject.constant.ResultCodeEnum;
import com.xhj.springbootproject.service.intf.RedisClient;
import com.xhj.springbootproject.util.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * @author ：Xionghaijun
 * @date ：Created in 2019/7/25 10:34 AM
 * @description： ；批量上传
 */
@Api(value = "文件上传",tags = "文件上传测试")
@RestController
public class BatchFileController {

    private final Logger logger = LoggerFactory.getLogger(BatchFileController.class);

    @Autowired
    private RedisClient redisClient;

    @RequestMapping(value = "/show", method = RequestMethod.GET)
    @ApiOperation(value = "show",notes = "打印日志测试接口")
    public JsonResult show() {
//        int i = 1 / 0;
        logger.debug("debug级别日志输入");
        logger.info("info级别日志输入");
        logger.warn("warm级别日志输入");
        logger.error("error级别日志输入");
        return JsonResult.getSuccessResult().fillData("整合数据");

    }

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ApiOperation(value = "upload",notes = "文件上传接口")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "file",name = "上传文件名称",dataType = "file"),
    })
    public JsonResult uploadFile(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) {
        try {
            String realPath = request.getServletContext().getRealPath("/upload");
            File fileDir = new File(realPath);
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }
            //生成文件在服务器端存放的名字
            for (int i = 0; i < files.length; i++) {
                String fileSuffix = files[i].getOriginalFilename().substring(files[i].getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID().toString() + fileSuffix;
                File file = new File(fileDir + "/" + fileName);
                files[i].transferTo(file);
            }
        } catch (Exception e) {
            logger.error("批量上传出错，错误信息 {}", e);
            return JsonResult.getFailedResult(ResultCodeEnum.INTERNAL_ERROR, "批量上传失败");
        }

        return JsonResult.getSuccessResult();
    }
}
